﻿using Microsoft.AspNetCore.Identity;
using PYNET.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Newtonsoft.Json;
using PYNET.Utils;
using Microsoft.AspNetCore.StaticFiles;
using PYNET.Data;

namespace PYNET.Controllers
{
    [Authorize(Roles ="Admin")]
    public class AcManaController : Controller
    {
        private readonly ArticleSystemDbContext _context;
        private readonly SignInManager<User> _signInManager;
        private readonly UserManager<User> _userManager;
        private readonly RoleManager<TIdentityRole> _roleManager;
        private readonly IWebHostEnvironment _env;
        public AcManaController(
            SignInManager<User> signInManager,
            UserManager<User> userManager,
            RoleManager<TIdentityRole> roleManager,
            ArticleSystemDbContext context,
            IWebHostEnvironment env)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _roleManager = roleManager;
            _context = context;
            _env = env;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult TotalManage()
        {
            return View();
        }

        public async Task<IActionResult> UserManage()
        {
            var users = await _userManager.Users.ToListAsync();
            List<UserWithRole> Users = new List<UserWithRole>();
            foreach (var user in users)
            {
                Users.Add(new UserWithRole
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    Email = user.Email,
                    RegistTime = user.RegistTime,
                    role = await _userManager.IsInRoleAsync(user, "Admin") ? "管理" : "普通用户"
                });
            }
            return View(Users);
        }

        [HttpGet]
        public async Task<IActionResult> UserEdit(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                return RedirectToAction("UserManage", "Account");
            }
            UserWithRole User = new UserWithRole
            {
                Id = user.Id,
                UserName = user.UserName,
                Email = user.Email,
                RegistTime = user.RegistTime,
                role = await _userManager.IsInRoleAsync(user, "Admin") ? "Admin" : "User"
            };
            return new JsonResult(User);
        }

        [HttpPost]
        public async Task<IActionResult> UserEdit()
        {
            UserWithRole user = new UserWithRole
            {
                UserName = Request.Form["UserName"],
                Email = Request.Form["Email"],
                role = Request.Form["Role"]
            };
            if (ModelState.IsValid)
            {
                var EditUser = await _userManager.FindByNameAsync(user.UserName);
                if (EditUser == null)
                {
                    //ModelState.AddModelError("", "不存在此用户");
                    new JsonResult("不存在此用户");
                }
                EditUser.UserName = user.UserName;
                EditUser.Email = user.Email;

                var result = await _userManager.UpdateAsync(EditUser);
                if (user.role == "User" && await _userManager.IsInRoleAsync(EditUser, "Admin"))
                {
                    var resultRole = await _userManager.RemoveFromRoleAsync(EditUser, "Admin");
                    if (result.Succeeded && resultRole.Succeeded)
                    {
                        return new JsonResult("成功！");
                    }
                }
                else
                {
                    var resultRole = await _userManager.AddToRoleAsync(EditUser, "Admin");
                    if (result.Succeeded && resultRole.Succeeded)
                    {
                        return new JsonResult("成功！");
                    }
                }
                return new JsonResult("失败！");
            }
            return new JsonResult("模型错误！");
        }

        [HttpPost]
        public async Task<IActionResult> UserDelete()
        {
            String Id = Request.Form["Id"];
            var user = await _userManager.FindByIdAsync(Id);
            if (user == null)
            {
                return new JsonResult("不存在此用户！");
            }
            var result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                return new JsonResult("成功！");
            }
            return new JsonResult("失败！");
        }

        public async Task<IActionResult> ArticleManage()
        {
            var Articles = await _context.Articles.ToListAsync();
            List<ArticleIndexViewModel> articleIndexViewModels = new List<ArticleIndexViewModel>();
            foreach (var article in Articles)
            {
                var name = await _userManager.FindByIdAsync(article.UId.ToString());
                if (name != null)
                {
                    articleIndexViewModels.Add(new ArticleIndexViewModel
                    {
                        AId = article.AId,
                        UserName = name.UserName,
                        Title = article.Title,
                        Content = article.Content,
                        LikeNumber = article.LikeNumber,
                        Introduce=article.Introduce
                    });
                }
                else
                {
                    articleIndexViewModels.Add(new ArticleIndexViewModel
                    {
                        AId = article.AId,
                        UserName = "已注销用户",
                        Title = article.Title,
                        Content = article.Content,
                        LikeNumber = article.LikeNumber,
                        Introduce = article.Introduce
                    });
                }
            }
            return View(articleIndexViewModels);
        }

        public IActionResult ArticleCreate()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ArticleCreate([Bind("Title,Introduce,Content,ArticlePicture")] Article article)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            article.UId = user.Id;
            article.LikeNumber = 0;
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(article);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(ArticleManage));
                }
            }
            catch
            {
                ModelState.AddModelError("", "因未知原因失败");
            }
            return View(article);
        }

        public async Task<IActionResult> ArticleEdit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var article = await _context.Articles.FindAsync(id);
            if (article == null)
            {
                return NotFound();
            }
            return View(article);

        }

        [Authorize(Roles = "Admin")]
        [HttpPost, ActionName("ArticleEdit")]
        public async Task<IActionResult> EditPost(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var articleToUpdate = await _context.Articles.FirstOrDefaultAsync(s => s.AId == id);
            if (await TryUpdateModelAsync<Article>(
                articleToUpdate,
                "",
                s => s.Title,s=>s.Introduce,s=>s.ArticlePicture, s => s.Content))
            {
                try
                {
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(ArticleManage));
                }
                catch (DbUpdateException)
                {
                    ModelState.AddModelError("", "因未知原因失败");
                }
            }
            return View(articleToUpdate);
        }

        [HttpPost]
        public async Task<IActionResult> ArticleDelete()
        {
            String id = Request.Form["Id"];
            
            if (id == null)
            {
                new JsonResult("不存在此文章！");
            }
            var article = await _context.Articles.FindAsync(Convert.ToInt32(id));
            if (article == null)
            {
                return new JsonResult("不存在此文章！");
            }
            try
            {
                _context.Articles.Remove(article);
                await _context.SaveChangesAsync();
                return new JsonResult("成功！");
            }
            catch (DbUpdateException /* ex */)
            {
                return new JsonResult("异常，失败！");
            }
        }


        public async Task<IActionResult> ArticleDetail(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var article = await _context.Articles.FindAsync(id);
            var name = await _userManager.FindByIdAsync(article.UId.ToString());
            if (name != null)
            {
                var ArticleWithUser = new ArticleIndexViewModel
                {
                    AId = article.AId,
                    UserName = name.UserName,
                    Title = article.Title,
                    Content = article.Content,
                    LikeNumber = article.LikeNumber,
                    Uid = article.UId
                };
                return View(ArticleWithUser);
            }
            else
            {
                var ArticleWithUser = new ArticleIndexViewModel
                {
                    AId = article.AId,
                    UserName = "已注销用户",
                    Title = article.Title,
                    Content = article.Content,
                    LikeNumber = article.LikeNumber,
                    Uid = article.UId
                };
                return View(ArticleWithUser);
            }
        }

        public async Task<IActionResult> ArticleRequestManage()
        {
            var Articles = await _context.ArticleRequests.ToListAsync();
            return View(Articles);
        }

        public async Task<IActionResult> ArticleAccept(int? id)
        {
            if (id == null) { 
                return NotFound();
            }
            var articleRequest = await _context.ArticleRequests.FindAsync(id);
            articleRequest.status = 1;
            var article = new Article {
                UId = articleRequest.UId,
                Title = articleRequest.Title,
                Content = articleRequest.Content,
                LikeNumber = 0,
                Introduce=articleRequest.Introduce,
                ArticlePicture=articleRequest.ArticlePicture
            };
            try
            {
                    await TryUpdateModelAsync<ArticleRequest>(
                    articleRequest,
                    "",
                    s => s.status);
                    _context.Add(article);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(ArticleRequestManage));
            }
            catch
            {
                ModelState.AddModelError("", "因未知原因失败");
            }
            return RedirectToAction(nameof(ArticleRequestManage));

        }

        public async Task<IActionResult> ArticleReject(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var articleRequest = await _context.ArticleRequests.FindAsync(id);
            articleRequest.status = 2;
            if (await TryUpdateModelAsync<ArticleRequest>(
                articleRequest,
                "",
                s => s.status))
            {
                try
                {
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(ArticleRequestManage));
                }
                catch (DbUpdateException)
                {
                    ModelState.AddModelError("", "因未知原因失败");
                }
            }
            return RedirectToAction(nameof(ArticleRequestManage));
        }

        public async Task<IActionResult> CommentManage()
        {
            var comments = await _context.Comments.ToListAsync();
            return View(comments);
        }

        public async Task<IActionResult> CommentDelete()
        {
            String id = Request.Form["Id"];

            if (id == null)
            {
                return new JsonResult("不存在此评论！");
            }
            var comment = await _context.Comments.FindAsync(Convert.ToInt32(id));
            if (comment == null)
            {
                return new JsonResult("不存在此评论！");
            }
            try
            {
                _context.Comments.Remove(comment);
                await _context.SaveChangesAsync();
                return new JsonResult("成功！");
            }
            catch (DbUpdateException)
            {
                return new JsonResult("异常，失败！");
            }
        }
    }
}
